<template>
    <!-- pages/site/addsite/index.wxml -->
    <view>
        <view class="box">
            <view class="flexbox-sb">
                <view class="centers">
                    <view class="text1">选择地区</view>
                    <view class="placeholder-class" @tap="showmolde">{{ city }}</view>
                </view>
                <view @tap="showmolde" class="centers">
                    <van-icon name="arrow-down" color="#FF8722" />
                </view>
                <!-- <view bindtap="getUserLocation" class="centers">
        <van-icon name="location-o" color="#FF8722" />
      </view> -->
            </view>
        </view>
        <!-- <view class="box">
    <view class="centers detail">
      <view class="text1">详细地址：</view>
      <textarea class="textarea" type="text" placeholder="请填写详细地址" placeholder-class="textarea-placeholder"
        model:value="{{location}}"></textarea>
    </view>
  </view> -->
        <view class="addbtn" @tap="onAdd">保存</view>
        <van-popup :show="show" position="bottom" @close="onClose">
            <van-area :area-list="areaList" :columns-num="3" title="选择城市" @cancel="onClose" @confirm="onFirm" />
        </van-popup>
    </view>
</template>

<script>
// pages/site/addsite/index.js
const app = getApp(); // 引入app

const _request = require('../../../utils/request.js'); // 引入require
// 引入SDK核心类，js文件根据自己业务，位置可自行放置

var QQMapWX = require('../../../utils/qqmap-wx-jssdk.min.js');

var qqmapsdk;

const area = require('../../../utils/area');

import { qqMapToBMap } from '../../../utils/util.js';
export default {
    data() {
        return {
            imgUrl: app.globalData.imgUrl,

            //全局img路径
            city: '省、市、区',

            GDId: [],
            show: false,

            // areaList: area.areaList,
            areaList: {},

            location: '',
            storeLocation: null,
            getArea: [],
            province: null,
            citydata: null,
            district: null,
            latitude: '',
            longitude: '',

            fixCode: {
                //自定义6位编码对应的原编码
                442001: '442000001',
                442002: '442000002',
                442003: '442000003',
                442004: '442000004',
                442005: '442000005',
                442006: '442000006',
                442007: '442000100',
                442008: '442000101',
                442009: '442000102',
                442010: '442000103',
                442011: '442000104',
                442012: '442000105',
                442013: '442000106',
                442014: '442000107',
                442015: '442000108',
                442016: '442000109',
                442017: '442000110',
                442018: '442000111',
                442019: '442000112',
                442020: '442000113',
                442021: '442000114',
                442022: '442000115',
                442023: '442000116',
                442024: '442000117'
            },

            cityGDId: '',
            districtGDId: '',
            provinceGDId: '',
            markers: ''
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        _request
            .get('/area/getAppletArea', {})
            .then((res) => {
                if (res.data.data && res.data.data.county_list) {
                    //控件只支持6数位编码, 将9位编码改为6位
                    let oldName = [
                        '442000001',
                        '442000002',
                        '442000003',
                        '442000004',
                        '442000005',
                        '442000006',
                        '442000100',
                        '442000101',
                        '442000102',
                        '442000103',
                        '442000104',
                        '442000105',
                        '442000106',
                        '442000107',
                        '442000108',
                        '442000109',
                        '442000110',
                        '442000111',
                        '442000112',
                        '442000113',
                        '442000114',
                        '442000115',
                        '442000116',
                        '442000117'
                    ];
                    let name = [
                        '442001',
                        '442002',
                        '442003',
                        '442004',
                        '442005',
                        '442006',
                        '442007',
                        '442008',
                        '442009',
                        '442010',
                        '442011',
                        '442012',
                        '442013',
                        '442014',
                        '442015',
                        '442016',
                        '442017',
                        '442018',
                        '442019',
                        '442020',
                        '442021',
                        '442022',
                        '442023',
                        '442024'
                    ];
                    res.data.data.county_list = this.renameObjProp(res.data.data.county_list, oldName, name); // console.log('---->', res.data.data.county_list)
                }

                this.setData({
                    areaList: res.data.data
                });
            })
            .catch((error) => {
                console.log(error, 'error');
            });
    },
    onShow() {
        // 获取区域
        // _request.get('/area/getArea', {}).then((res) => {
        //   this.setData({
        //     getArea: res.data.data
        //   })
        // }).catch((error) => {
        //   console.log(error, 'error');
        // })
    },
    methods: {
        // 展示选择城市
        showmolde() {
            this.setData({
                show: true
            });
        },

        // 关闭选择城市
        onClose() {
            this.setData({
                show: false
            });
        },

        // 获取省市区id
        getAreaFun(area, city, district) {
            this.getArea.map((item) => {
                if (item.name == area && item.name != '北京市' && item.name != '重庆市' && item.name != '上海市' && item.name != '天津市') {
                    this.setData({
                        province: item
                    });
                    item.areaList.map((item) => {
                        if (item.name == city) {
                            this.setData({
                                citydata: item
                            });
                            item.areaList.map((item) => {
                                if (item.name == district) {
                                    this.setData({
                                        district: item
                                    });
                                }
                            });
                        }
                    });
                } else if (item.name == area && (item.name == '北京市' || item.name == '上海市' || item.name == '天津市')) {
                    this.setData({
                        province: item
                    });
                    this.setData({
                        citydata: item.areaList[0]
                    });
                    item.areaList[0].areaList.map((item) => {
                        if (item.name == district) {
                            this.setData({
                                district: item
                            });
                        }
                    });
                } else if (item.name == area && item.name == '重庆市') {
                    this.setData({
                        province: item
                    });
                    this.setData({
                        citydata: item
                    });
                    item.areaList.map((item) => {
                        item.areaList.map((item) => {
                            if (item.name == district) {
                                this.setData({
                                    district: item
                                });
                            }
                        });
                    });
                }
            });
        },

        // 完成选择城市，发送请求
        onFirm(e) {
            this.setData({
                show: false,
                city: e.detail.values.map((item) => {
                    return item.name;
                }),
                GDId: e.detail.values.map((item) => {
                    return item.code;
                })
            });

            if (this.fixCode[this.GDId[2]]) {
                this.setData({
                    ['GDId[2]']: this.fixCode[this.GDId[2]]
                });
            }

            this.setData({
                cityGDId: this.GDId[1],
                districtGDId: this.GDId[2],
                provinceGDId: this.GDId[0]
            });
        },

        // 获取用户定位
        getUserLocation() {
            let vm = this;
            uni.getSetting({
                success(res) {
                    // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
                    // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
                    // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
                    if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
                        uni.showModal({
                            title: '请求授权当前位置',
                            content: '需要获取您的地理位置，请确认授权',
                            success: function (res) {
                                if (res.cancel) {
                                    uni.showToast({
                                        title: '拒绝授权',
                                        icon: 'none',
                                        duration: 2000
                                    });
                                } else if (res.confirm) {
                                    uni.openSetting({
                                        success: function (dataAu) {
                                            if (dataAu.authSetting['scope.userLocation'] == true) {
                                                uni.showToast({
                                                    title: '授权成功',
                                                    icon: 'success',
                                                    duration: 2000
                                                }); //再次授权，调用wx.getLocation的API

                                                vm.getLocation();
                                            } else {
                                                uni.showToast({
                                                    title: '授权失败',
                                                    icon: 'none',
                                                    duration: 2000
                                                });
                                            }
                                        }
                                    });
                                }
                            }
                        });
                    } else if (res.authSetting['scope.userLocation'] == undefined) {
                        // 不存在就获取权限
                        vm.getLocation();
                    } else {
                        //调用wx.getLocation的API
                        vm.getLocation();
                    }
                }
            });
        },

        // 授权定位权限
        getLocation() {
            var _this = this;

            let location;
            uni.getLocation({
                type: 'wgs84',
                success: function (res) {
                    // location = qqMapToBMap(res.longitude, res.latitude)
                    location = res; // 实例化API核心类

                    qqmapsdk = new QQMapWX({
                        key: 'MBEBZ-6VQCP-EYSDK-LT7FQ-2LNUS-G4BTN'
                    }); // 经纬度转城市

                    qqmapsdk.reverseGeocoder({
                        //位置坐标
                        location: {
                            latitude: location.latitude,
                            longitude: location.longitude
                        },
                        //get_poi: 1, //是否返回周边POI列表：1.返回；0不返回(默认),非必须参数
                        success: function (res) {
                            //成功后的回调
                            var res = res.result;
                            var mks = [];
                            mks.push({
                                // 获取返回结果，放到mks数组中
                                title: res.address,
                                id: 0,
                                latitude: res.location.lat,
                                longitude: res.location.lng,
                                iconPath: '/static/firstpages/information/site/resources/placeholder.png',
                                //图标路径
                                width: 20,
                                height: 20,
                                callout: {
                                    //在markers上展示地址名称，根据需求是否需要
                                    content: res.address,
                                    color: '#000',
                                    display: 'ALWAYS'
                                },
                                ad_info: res.ad_info,
                                address_component: res.address_component
                            });

                            if (res.ad_info.city != '东莞市') {
                                _this.getAreaFun(res.ad_info.province, res.ad_info.city, res.ad_info.district);
                            } else {
                                _this.getAreaFun(res.ad_info.province, res.ad_info.city, res.address_reference.town.title);
                            }

                            _this.setData({
                                //设置markers属性和地图位置poi，将结果在地图展示
                                markers: mks,
                                city: res.ad_info.province + ',' + res.ad_info.city + ',' + res.ad_info.district,
                                latitude: res.location.lat,
                                longitude: res.location.lng
                            });
                        },
                        fail: function (error) {
                            console.error(error);
                        },
                        complete: function (res) {}
                    }); // 储存地址

                    uni.setStorageSync('location', res);
                },
                fail: function (error) {
                    console.log(error, 'error');
                }
            });
        },

        renameObjProp(data, oldName, name) {
            if (data) {
                for (let i = 0; i < oldName.length; i++) {
                    data[name[i]] = data[oldName[i]];
                    delete data[oldName[i]];
                }
            }

            return data;
        },

        onAdd: function () {
            const { location, province, citydata, district, latitude, longitude, city, GDId } = this;

            if (city === '省、市、区') {
                uni.showToast({
                    title: '请选择地区',
                    icon: 'none'
                });
                return;
            }

            const pages = getCurrentPages(); //获取页面栈堆

            const prev = pages[pages.length - 2]; //-2即为父级页面，想跳两层的话就-3

            prev.setData({
                //用setData()的特性给父级页面赋值并重新渲染
                location,
                province,
                citydata,
                district,
                latitude,
                longitude,
                city,
                GDId
            });
            uni.navigateBack({
                delta: 1
            });
        }
    }
};
</script>
<style>
.box {
    background: #ffffff;
    border-radius: 10rpx;
    padding: 20rpx;
    margin: 20rpx;
    box-sizing: border-box;
}

.h-86 {
    height: 86rpx;
    width: 100%;
    border-bottom: 1px solid #e8e8e8;
}

.text1 {
    font-size: 30rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #333333;
    width: 180rpx;
}

.detail {
    padding-top: 20rpx;
}

.detail > .text1 {
    position: relative;
    top: -65rpx;
}

/* .textarea {
  height: 100rpx;
  width: 500rpx;
} */

.textarea {
    width: 600rpx;
    height: 200rpx;
    background: #fbfbfb;
    padding: 20rpx;
    box-sizing: border-box;
    font-size: 28rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #999999;
    padding-bottom: 40rpx;
}

.textarea-placeholder {
    font-size: 28rpx;
    color: #999999;
}

.placeholder-class {
    font-size: 28rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #999999;
}

.site-text2 {
    font-size: 24rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #666666;
    line-height: 36rpx;
}

.iconbox {
    width: 24rpx;
    height: 24rpx;
    border: 1px solid #999999;
    border-radius: 50%;
}

.iconbox1 {
    border: 1px solid #ff8722;
}

.addbtn {
    width: 690rpx;
    height: 90rpx;
    background: #ff8722;
    border-radius: 45rpx;
    font-size: 36rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #f3f3f3;
    line-height: 90rpx;
    text-align: center;
    position: fixed;
    bottom: 50rpx;
    margin: 30rpx;
}

page {
    background-color: #fbfbfb;
}
</style>
